#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
db_routers.py
@Author: kindey
@Date: 2025/8/4
@Description: 
"""

class DatabaseRouter:
    """
    数据库路由控制器
    """

    route_app_labels = {
        'source': 'source',
        'result': 'result'
    }

    def db_for_read(self, model, **hints):
        """
        决定读取操作使用哪个数据库
        """
        if model._meta.app_label in self.route_app_labels:
            return self.route_app_labels[model._meta.app_label]
        return None

    def db_for_write(self, model, **hints):
        """
        决定写入操作使用哪个数据库
        """
        if model._meta.app_label in self.route_app_labels:
            return self.route_app_labels[model._meta.app_label]
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        决定是否允许两个对象之间有关系
        """
        db_set = {'source', 'result'}
        if obj1._state.db in db_set and obj2._state.db in db_set:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        决定某个数据库是否可以进行迁移
        """
        if app_label in self.route_app_labels:
            return db == self.route_app_labels[app_label]
        elif db in self.route_app_labels.values():
            return False
        return db == 'result'
